import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Modal, Form, Input, message as msg } from 'antd';

@connect(({ sysUser, loading }) => ({
  modal: sysUser.resetPwModal,
  submitting: loading.effects['sysUser/resetPassword'],
}))
@Form.create()
class ResetPasswordModal extends PureComponent {
  handleModalCancel = () => {
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({ type: 'sysUser/closeResetPwModal' });
  };

  handleModalOk = () => {
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        dispatch({ type: 'sysUser/resetPassword', payload: values }).then(({ code, message }) => {
          if (code === 0) {
            msg.success('操作成功');
            this.handleModalCancel();
          } else {
            msg.error(message);
          }
        });
      }
    });
  };

  render() {
    const {
      form,
      modal: { data, visible },
      submitting,
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
    };
    return (
      <Modal
        title='重置密码'
        visible={visible}
        confirmLoading={submitting}
        onCancel={this.handleModalCancel}
        onOk={this.handleModalOk}
      >
        {form.getFieldDecorator('userId', { initialValue: data.userId })}
        <Form.Item label="新密码" {...formItemLayout}>
          {form.getFieldDecorator('newPassword', {
            rules: [
              {
                type: 'string',
                required: true,
                message: '密码不能为空！',
              },
            ],
            initialValue: '',
          })(<Input />)}
        </Form.Item>
      </Modal>
    );
  }
}

export default ResetPasswordModal;
